package internal

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
	"yh-oss-convert/config"
)

var MyLog *zap.SugaredLogger

func initLogConfig() {
	var atom zap.AtomicLevel
	if config.MyConfig.Debug {
		atom = zap.NewAtomicLevelAt(zap.DebugLevel)
	} else {
		atom = zap.NewAtomicLevelAt(zap.InfoLevel)
	}
	hook := zapcore.AddSync(&lumberjack.Logger{
		Filename:   "./log/log.log",
		MaxSize:    10, // megabytes
		MaxBackups: 10,
		MaxAge:     28, // days
	})
	encoderConfigFile := zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,                        // 小写编码器
		EncodeTime:     zapcore.TimeEncoderOfLayout("[2006-01-02 15:04:05]"), // ISO8601 UTC 时间格式
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.FullCallerEncoder, // 全路径编码器
	}

	encoderConfigConsole := zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseColorLevelEncoder,                 // 小写编码器
		EncodeTime:     zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05"), // ISO8601 UTC 时间格式
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder, // 全路径编码器
	}
	coreFile := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encoderConfigFile),
		zapcore.NewMultiWriteSyncer(zapcore.AddSync(hook)),
		atom,
	)
	coreConsole := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encoderConfigConsole),
		zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout)),
		atom,
	)
	logger := zap.New(zapcore.NewTee(coreFile, coreConsole), zap.AddCaller())
	defer logger.Sync()
	MyLog = logger.Sugar()
}
